<script setup lang="ts">
import { ref, toRaw } from 'vue'
import {
    talkListService, addTalkService,
    updateTalkService, deleteTalkService,
    deleteBatchTalkService
} from "@/api/talk"
import { ElMessage, ElMessageBox } from 'element-plus'
import TextEditor from '@/component/TextEditor.vue'
import {
    Delete,
} from '@element-plus/icons-vue'

const talk = ref([
    {
        "id": 1,
        "author": "zhangSan",
        "content": "测试",
        "status": 1,
        "createTime": "",
        "updateTime": ""
    }
])

//分页条数据模型
const page = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数
const status = ref(undefined)
const talkList = async () => {
    let params = {
        page: page.value,
        pageSize: pageSize.value,
        status: status.value
    }
    let result = await talkListService(params)

    //渲染视图
    total.value = result.data.total;
    talk.value = result.data.records;
}
//调用函数查询
talkList();
//当每页条数发生了变化，调用此函数
const handleSizeChange = (size: number) => {
    pageSize.value = size
    talkList();
}
//当前页码发生变化，调用此函数
const handleCurrentChange = (num: number) => {
    page.value = num
    talkList();
}
//通过按钮点击展示内容（因为富文本大多时候内容很长）
const content1 = ref("")
const visibleDialog1 = ref(false)
const showContent = (content: string) => {
    visibleDialog1.value = true
    content1.value = content
}
//添加说说表单模型
const talkForm = ref({
    id: 1,
    content: "",
    status: undefined,
})
//添加说说的表单校验模型
const Rules = ref({
    status: [
        { required: true, message: '请选择说说状态', trigger: 'blur' }
    ]
})

//默认不显示抽屉
const visibleDrawer = ref(false)
//为抽屉添加响应数据
const addTalkRef = ref()
//后台调用添加用户接口
const onAdd = async () => {
    //点击添加按钮后再进行二次校验
    await addTalkRef.value?.validate().catch((err: any) => { ElMessage.error("校验失败"); return Promise.reject(err) })
    let result = await addTalkService(talkForm.value) as any;
    ElMessage.success(result.msg ? result.msg : '添加成功')
    //让抽屉消失
    visibleDrawer.value = false
    //刷新列表
    talkList();
}
//刷新抽屉表单
const clearTalkForm = () => {
    talkForm.value = {
        id: 1,
        content: "",
        status: undefined,
    }
}
//取消添加
const cancelDrawer = () => {
    visibleDrawer.value = false
}
//添加说说表单模型
const talkStatusForm = ref({
    id: 1,
    status: 1,
})
//修改说说状态
const onUpdate = async (row: { id: any, status: any }) => {
    if (row.status === 1) {
        talkStatusForm.value.id = row.id
        talkStatusForm.value.status = 0
        let result = await updateTalkService(talkStatusForm.value) as any
        ElMessage.success(result.msg ? result.msg : '修改成功')
        //刷新列表
        talkList();
    } else {
        talkStatusForm.value.id = row.id
        talkStatusForm.value.status = 1
        let result = await updateTalkService(talkStatusForm.value) as any
        ElMessage.success(result.msg ? result.msg : '修改成功')
        //刷新列表
        talkList();
    }
}
//删除
const deleteTalk = (row: { id: any }) => {
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result = await deleteTalkService(row.id) as any;
            ElMessage({
                type: 'success',
                message: result.msg ? result.msg : '删除成功',
            })
            talkList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
//批量删除
const arr = ref([])
const handleSelectionChange = (rows: any) => {
    arr.value = rows.map((i: { id: any }) => i.id)
}
const deleteBatchTalk = () => {
    if (arr.value.length === 0) {
        ElMessage.error("请选择数据")
        return
    }
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let ids = toRaw(arr.value)
            let params = {
                ids: ids
            }
            let result = await deleteBatchTalkService(params) as any;
            ElMessage({
                type: 'success',
                message: result.msg ? result.msg : '删除成功',
            })
            talkList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>说说管理</span>
                <div>
                    <el-button type="primary" @click="visibleDrawer = true; clearTalkForm()">发布说说</el-button>
                    <el-button type="danger" @click="deleteBatchTalk()">批量删除</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item prefix-icon="name" label="说说状态：">
                <el-select placeholder="请选择" v-model="status" style="width: 240px">
                    <el-option label="公开" value=1></el-option>
                    <el-option label="私有" value=0></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="talkList()">搜索</el-button>
                <el-button @click="status = undefined">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 文章列表 -->
        <el-table :data="talk" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" width="100">
                <template v-slot="scope">
                    <!-- 序号实现自动增加且连续 -->
                    {{ (page - 1) * pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="说说内容" prop="content" show-overflow-tooltip width="120">
                <template v-slot="scope">
                    <el-button type="info" @click="showContent(scope.row.content)">显示内容</el-button>
                </template>
            </el-table-column>
            <el-table-column align="center" label="说说状态" prop="status" width="120">
                <!-- 将渲染的1，0转换为公开，私有 -->
                <template v-slot="scope">{{ scope.row.status === 1 ? '公开' : '私有' }}</template>
            </el-table-column>
            <el-table-column label="发布人" prop="author" width="120"></el-table-column>
            <el-table-column label="发布时间" prop="createTime" width="200"></el-table-column>
            <el-table-column label="修改时间" prop="updateTime" width="200"></el-table-column>
            <el-table-column label="操作" width="400">
                <template #default="{ row }">
                    <el-button type="primary" text link @click="onUpdate(row)">{{ row.status === 1 ? '私有' :
                        '公开' }}</el-button>
                    <el-button :icon="Delete" plain type="danger" @click="deleteTalk(row)">删除</el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" background
            layout="sizes,prev, pager,next,jumper,total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :total="total">
        </el-pagination>

        <!-- 显示富文本内容对话框 -->
        <el-dialog title="内容" v-model="visibleDialog1" width="60%">
            <div class="w-e-text">
                <div v-html="content1"></div>
            </div>
            <div>
                <el-button type="primary" @click="visibleDialog1 = false">返 回</el-button>
            </div>
        </el-dialog>

        <!-- 抽屉中嵌套添加表单 -->
        <el-drawer v-model="visibleDrawer" title="添加说说" direction="rtl" destroy-on-close size="45%">
            <div>
                <el-form ref="addTalkRef" :model="talkForm" :rules="Rules">
                    <el-form-item label="说说状态" prop="status">
                        <el-select placeholder="请选择" v-model="talkForm.status">
                            <el-option label="公开" value="1"></el-option>
                            <el-option label="私有" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="说说内容">
                        <TextEditor v-model="talkForm.content" />
                    </el-form-item>
                </el-form>
                <!-- 按钮设置 -->
                <div>
                    <el-button @click="cancelDrawer(); clearTalkForm()">取消</el-button>
                    <el-button type="primary" @click="onAdd">
                        添加
                    </el-button>
                </div>
            </div>
        </el-drawer>
    </el-card>
</template>



<style scoped lang="scss">
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>